//
//  LXCarOrderApplyViewController.m
//  ZuLinProject
//
//  Created by bancheng on 2022/2/15.
//  Copyright © 2021 LX_App. All rights reserved.
//

#import "LXCarOrderApplyViewController.h"
#import "LXCarOrderModel.h"
#import "LXTableViewCell.h"
#import "LXUpContractTableViewCell.h"
@interface LXCarOrderApplyViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UILabel *headLb;
@property (weak, nonatomic) IBOutlet UILabel *footLb;
@property (nonatomic) NSMutableDictionary *loanDic;
@property (nonatomic) NSDictionary *selDic;


@property (weak, nonatomic) IBOutlet UIView *contractHeadBackView;
@property (weak, nonatomic) IBOutlet UIView *contractFootBackView;
@property (weak, nonatomic) IBOutlet UIButton *contractHeadBtn;
@property (weak, nonatomic) IBOutlet UIButton *contractFootBtn;
@property (weak, nonatomic) IBOutlet UIButton *headDelBtn;
@property (weak, nonatomic) IBOutlet UIButton *footDelBtn;
@property (nonatomic) NSString *contractHeadUrl,*contractFootUrl;


@property (nonatomic) UITableView *tableView;
@property (nonatomic) NSMutableArray *data;


@end

@implementation LXCarOrderApplyViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.type == 1) {
        self.customerTitleLabel.text = @"新增签约";
    }
    else {
        self.customerTitleLabel.text = @"签约详情";
    }
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self.view addSubview:self.tableView];
    
    [self.tableView registerClass:[LXTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LXTableViewCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXUpContractTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([LXUpContractTableViewCell class])];
    

    [self loadData];
    
    
   
    if (self.type == 1) {
        [self setBottomViewWithText:@"确认签约"];
        self.tableView.height = kScreenHeight - LL_StatusBarAndNavigationBarHeight - kComHeight;
        self.tableView.tableFooterView = [self setTableFooter];
    }

    
    
    
}
-(UIView *)setTableFooter{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, ScreenWidth - 40, 40)];
    label.text = @"*请上传合同首页和尾页盖章页，图片格式为.jpg、.png,图片大小在1M以内，并保证字迹清晰。";
    label.font = Fond10;
    label.textColor = ColorWithAAAAAA;
    label.numberOfLines = 0;
    [label addAttributes:TextAttrCorlor(UIColor.redColor) forString:@"*" size:0];
    [view addSubview:label];
    return view;
}

- (void)loadData{
    
    self.loanDic  = [NSMutableDictionary dictionary];
    
   
   
    [self.loanDic setValue:self.orderModel.beginTime forKey:@"beginTime"];
    
    [self.loanDic setValue:self.orderModel.endTime forKey:@"endTime"];
    
    
    self.contractHeadUrl = self.orderModel.firstPic;
    
    self.contractFootUrl = self.orderModel.lastPic;
    

    self.data = @[
        @{
            @"title":@"合约开始时间",
            @"key":@"beginTime",
            @"placeHolder" : @"请选择开始时间",
            @"canEdit":@(NO),
            @"showAccess":self.type==1?@(YES):@(NO),
            @"maxLength":@(10000),
            @"sel":self.type==1?@"clickBeginTime":@"",
            @"height":@(kComHeight)
        },
        @{
            @"title":@"合约结束时间",
            @"key":@"endTime",
            @"placeHolder" : @"请选择结束时间",
            @"canEdit":@(NO),
            @"showAccess":self.type==1?@(YES):@(NO),
            @"maxLength":@(10000),
            @"sel":self.type==1?@"clickEndTime":@"",
            @"height":@(kComHeight)
        },
        @{
            @"title":self.type==1?@"上传合同首页":@"合同首页",
            @"key":@"contractHead",
            @"height":@(250)
        },
        @{
            @"title":self.type==1?@"上传合同尾页":@"合同尾页",
            @"key":@"contractFoot",
            @"height":@(250),
        }
        
        
    ].mutableCopy;
    
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.data[indexPath.row];
    return [dic[@"height"] doubleValue];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *dic = self.data[indexPath.row];

    // 合同首页
    if ([dic[@"key"] isEqualToString:@"contractHead"]||[dic[@"key"] isEqualToString:@"contractFoot"]) {
        LXUpContractTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXUpContractTableViewCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setClipsToBounds:YES];
//        [cell.backView setLineDashPattern:@[@4,@2] withColor:[UIColor colorWithHexString:@"#C4C4C4"] withCornerRadius:10];

        cell.titleLb.text = dic[@"title"];
        
        if ([dic[@"key"] isEqualToString:@"contractHead"]) {
            if (!StringIsEmpty(self.contractHeadUrl)) {
                [cell.contractBtn sd_setImageWithURL:[NSString URLStrEncoding:[NSString stringWithFormat:@"%@%@",HTTP_URL,self.contractHeadUrl]] forState:UIControlStateNormal placeholderImage:kImg(@"上传合同")];
                cell.delBtn.hidden = self.type==1?NO:YES;
            }
            else
            {
                [cell.contractBtn setImage:kImg(@"上传合同") forState:UIControlStateNormal];
                cell.delBtn.hidden = YES;
            }
            
        }
       
        
       else if([dic[@"key"] isEqualToString:@"contractFoot"]){
           if (!StringIsEmpty(self.contractFootUrl)) {
               cell.delBtn.hidden = self.type==1?NO:YES;
               [cell.contractBtn sd_setImageWithURL:[NSString URLStrEncoding:[NSString stringWithFormat:@"%@%@",HTTP_URL,self.contractFootUrl]] forState:UIControlStateNormal placeholderImage:kImg(@"上传合同")];
           }
           else{
               [cell.contractBtn setImage:kImg(@"上传合同") forState:UIControlStateNormal];
               cell.delBtn.hidden = YES;
           }
            
        }
        
        
       
        
        //添加
        [cell.contractBtn whenTapped:^{

            if ([dic[@"key"] isEqualToString:@"contractHead"]) {
                [self contractHeadAction:cell];
            }
            else  {
                [self contractFootAction:cell];
            }
            
        }];
        
        // 删除
        [cell.delBtn whenTapped:^{
            cell.delBtn.hidden = YES;
            if ([dic[@"key"] isEqualToString:@"contractHead"]) {
                self.contractHeadUrl = nil;
            }
            else {
                self.contractFootUrl = nil;
            }
            [cell.contractBtn setImage:kImg(@"上传合同") forState:UIControlStateNormal];

        }];
        
        return cell;
    }
    
 
    LXTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setClipsToBounds:YES];
    

    cell.cellDic = dic;
    cell.textFiled.hidden = NO;
    cell.subTitleLab.hidden = YES;
    cell.textFiled.text = self.loanDic[dic[@"key"]];
    
    
    cell.textfiledChangeBlock = ^(NSString * _Nonnull textStr) {
        self.loanDic[dic[@"key"]]  = textStr;
    };
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dic = self.data[indexPath.row];
    NSString * selName = dic[@"sel"];
    self.selDic = dic;
    SEL action = NSSelectorFromString(selName);
    if ([self respondsToSelector:action]) {
        [self performSelector:action withObject:nil afterDelay:0];
    }

}

#pragma mark -- 选择开始日期
-(void)clickBeginTime{
    [self.view endEditing:YES];
    DatePickView *datePicker =[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.loanDic[@"beginTime"] withIsMaxDate:YES withNoForward:NO WithTips:@"请选择开始日期"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    WEAKSELF
    datePicker.block = ^(NSString *yearString){
        
        
        if([NSString compareDate:self.loanDic[@"endTime"] withDate:yearString withFormat:k_DateFormat]==1){
            showAlert(@"开始日期不能大于结束日期");
        }
        else {
            [weakSelf.loanDic setObject:yearString forKey:weakSelf.selDic[@"key"]];
            [weakSelf.tableView reloadData];
        }
        
    };
}

#pragma mark -- 选择结束日期
-(void)clickEndTime{
    [self.view endEditing:YES];
    DatePickView *datePicker =[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.loanDic[@"endTime"] withIsMaxDate:YES withNoForward:NO WithTips:@"请选择结束日期"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    WEAKSELF
    datePicker.block = ^(NSString *yearString){
        if([NSString compareDate:self.loanDic[@"beginTime"] withDate:yearString withFormat:k_DateFormat]==-1){
            showAlert(@"结束日期不能小于开始日期");
        }
        else {
            [weakSelf.loanDic setObject:yearString forKey:weakSelf.selDic[@"key"]];
            [weakSelf.tableView reloadData];
        }
        
    };
}


#pragma mark -- 合同首页
- (void)contractHeadAction:(LXUpContractTableViewCell *)cell {

    if (StringIsEmpty(self.contractHeadUrl)) {
        
        [[LXPhotoHelper shareHelper] showImageViewSelcteWithResultBlock:^(NSDictionary *dic) {
            cell.delBtn.hidden = NO;
            self.contractHeadUrl = [NSString stringWithFormat:@"%@",dic[@"url"]];
            [cell.contractBtn sd_setImageWithURL:[NSString URLStrEncoding:[NSString stringWithFormat:@"%@%@",HTTP_URL,dic[@"url"]]] forState:UIControlStateNormal];
        }];
    }
    else {
        
        [self showBigImage:cell.contractBtn.currentImage];
    
    }
}
    

#pragma mark -- 合同尾页
- (void)contractFootAction:(LXUpContractTableViewCell *)cell {
    
    if (StringIsEmpty(self.contractFootUrl)) {
        [[LXPhotoHelper shareHelper] showImageViewSelcteWithResultBlock:^(NSDictionary *dic) {
            cell.delBtn.hidden = NO;
            self.contractFootUrl = [NSString stringWithFormat:@"%@",dic[@"url"]];
            [cell.contractBtn sd_setImageWithURL:[NSString URLStrEncoding:[NSString stringWithFormat:@"%@%@",HTTP_URL,dic[@"url"]]] forState:UIControlStateNormal];
        }];
    }
    else {
        
        [self showBigImage:cell.contractBtn.currentImage];
        
        [cell.delBtn whenTapped:^{
            cell.delBtn.hidden = YES;
            self.contractFootUrl = nil;
            [cell.contractBtn setImage:kImg(@"上传合同") forState:UIControlStateNormal];
        }];
    }
    
}
-(void)showBigImage:(UIImage *)image{
    UIWindow *window = [BaseViewController getCurrentWindow];
    ShowBigImageWithFrameView *ImageShow = [[ShowBigImageWithFrameView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, B_HEIGHT) withImage:image];
    [window addSubview:ImageShow];
}

#pragma mark -- 确认签约
- (void)clickBottomView:(UIButton *)sender{
    
 
    if (StringIsEmpty(self.loanDic[@"beginTime"])) {
        showAlert(@"请选择合同开始时间");
        return;
    }
    
    if (StringIsEmpty(self.loanDic[@"endTime"])) {
        showAlert(@"请选择合同结束时间");
        return;
    }
    if (StringIsEmpty(self.contractHeadUrl)) {
        showAlert(@"请上传合同首页");
        return;
    }
    
    if (StringIsEmpty(self.contractFootUrl)) {
        showAlert(@"请上传合同尾页");
        return;
    }
    
  

    [Tool showAlertTitle:@"温馨提示" msg:@"确认签约" cancelTitle:@"取消" commitBtnTitle:@"确定" cancelHandlerBlock:^{
    } commitHandlerBlock:^{
        NSDictionary *dic = @{
            @"id":self.orderModel.ID,
            @"beginTime":self.loanDic[@"beginTime"],
            @"endTime":self.loanDic[@"endTime"],
            @"carId":self.orderModel.carId,
            @"firstPic":self.contractHeadUrl,
            @"lastPic":self.contractFootUrl
            
        };
        [MSNetworkManager postRevertUrl:TBookingReloadContract_URL params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {

            if (isSuccess) {
                showAlert(@"签约成功");
                kUserDefaultSetBool(YES, kRefreshStr);
                [self.navigationController popViewControllerAnimated:YES];
                [self.navigationController popViewControllerAnimated:YES];
            }
            
            
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
            
        } withShowHud:YES];
    } onVC:self];
    
}


- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, LL_StatusBarAndNavigationBarHeight, ScreenWidth, kScreenHeight - LL_StatusBarAndNavigationBarHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.contentInset = UIEdgeInsetsMake(0,0,kComHeight + 10,0);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    }
    return _tableView;
}

@end
